function randomInt(min,max){
	return Math.floor(Math.random()*(max-min+1))+min
}
function randomFloat(min, max){
	return Math.random()*(max-min)+min
}

function calHandPos(x, y, r, l){
	pos_x = x + Math.cos(l) * r
	pos_y = y + Math.sin(l) * r
	return {pos_x, pos_y}
}

function calPosByLAndTan(x, y, len, tana){
	l = Math.atan(tana)
	pos_x1 = x + Math.cos(l) * len
	pos_y1 = y + Math.sin(l) * len
	pos_x2 = x - Math.cos(l) * len
	pos_y2 = y - Math.sin(l) * len
	return {pos_x1, pos_y1,pos_x2,pos_y2}
}

function getRad(degree){
	return degree/180*Math.PI;
}

function getParaCurve(x1, y1, x2, y2){
	let d = x1*x1*x2 - x1*x2*x2
	let dx = y1 * x2 - x1 * y2
	let dy = x1 * x1 * y2  - y1 * x2 * x2
	let a = dx / d
	let b = dy / d
	return {
		ParaCurveFunction: function(x){
 			return a * x * x + b * x
		},
		GradientFunction: function(x){
			return 2 * a * x + b
		}
	}
}

var beginTime = undefined
var dt = 0
var game_begin = false
var game_over = false
const javelin_speed = 370
const hand_last_time = 0.7

const canvas_width = 1200
const canvas_height = 300

var str_bar_mx = 100 
var str_bar_mHalfWidth = 50
var str_bar_width = 400
var str_bar_height = 100
var bar_height = 25
var bar_indicator_Halfwidth = 20
var bar_indicator_height = 30
var bar_indicator_x = 100
var bar_indicator_y = bar_indicator_height + bar_height
var str_bar_speed = 150
var str_bar_time = undefined

var score_range = [500, 2500]
var fall_ground_range = [canvas_width/5, canvas_width - 10]

var score = []
//标枪落点的x值
var end_x = 1000
// function calScale(){
// 	let tmp_d = Math.abs(str_bar_mx - bar_indicator_x)
// 	if(tmp_d == 0){
// 		tmp_d = 1
// 	}else{
// 		tmp_d = 7/Math.abs(str_bar_mx - bar_indicator_x)
// 		if(tmp_d > 1){
// 			tmp_d = 1
// 		}
// 	}
// 	return tmp_d
// }

function calScale(){
	let mid_s_pos = 0
	let left_s_pos = 0
	let right_s_pos = 1
	let tmp_d = Math.abs(str_bar_mx - bar_indicator_x)
	if(tmp_d <= str_bar_mHalfWidth){
		//left_s_pos = mid_s_pos
		left_s_pos = 0.1
		right_s_pos = 1
		tmp_d = tmp_d/str_bar_mHalfWidth
	}else{
		left_s_pos = 0
		//right_s_pos = mid_s_pos
		right_s_pos = 0.1
		tmp_d = tmp_d/str_bar_width
	}
	return right_s_pos - (right_s_pos - left_s_pos) * tmp_d
}

function calScore(){
	//score = score_range[1] - ((score_range[1] - score_range[0]) *Math.abs(str_bar_mx - bar_indicator_x) / str_bar_width)
	new_score = score_range[0] + (score_range[1] - score_range[0]) * calScale()
	new_score = Math.floor(new_score)
	score.push(new_score)
	while(score.length > 4){
		score.shift()
	}
	setScoreRecorder()
	return new_score
}


function removeAllScores(){
	score.length = 0
	setScoreRecorder()
}

function removeLastScore(){
	if(score.length > 0){
		score.length -= 1
	}
	setScoreRecorder()
}

function setScoreRecorder(){
	let srs = document.getElementById('scores')
	let tmp_pos = 0
	for(tmp_pos = 0; tmp_pos < srs.childElementCount && tmp_pos < score.length; tmp_pos++){
		srs.children[tmp_pos].innerHTML = score[tmp_pos]
	}
	while(tmp_pos < score.length){
		let new_score_node = document.createElement('div')
		new_score_node.setAttribute('class', 'score_item')
		new_score_node.innerHTML = score[tmp_pos]
		srs.appendChild(new_score_node)
		tmp_pos++
	}
	while(tmp_pos < srs.childElementCount){
		srs.children[tmp_pos].remove()
	}
}

function calEndX(){
	//end_x = fall_ground_range[1] - ((fall_ground_range[1] - fall_ground_range[0]) * Math.abs(str_bar_mx - bar_indicator_x) / str_bar_width)
	end_x = fall_ground_range[0] + (fall_ground_range[1] - fall_ground_range[0]) * calScale()
	return end_x
}


function resetStrBar(){
	str_bar_mx = randomFloat(str_bar_mHalfWidth, str_bar_width - str_bar_mHalfWidth)
	bar_indicator_x = 0
	str_bar_time = Date.now()
}

function draw_canvas(){
	if(game_over){
		return
	}
	if(game_begin){
		dt = (Date.now() - beginTime) / 1000
	}

	let canvas = document.getElementById('gamebox');
	if(!canvas.getContext) return;
	canvas.width=canvas_width;
	canvas.height=canvas_height;
	var ctx = canvas.getContext('2d');
	// ctx.fillStyle = "rgb(100,100,0)";
	// ctx.fillRect (0, 0, canvas_width, canvas_height);

	//将画布坐标改为笛卡尔系坐标
	let ground_float = 45
    ctx.translate(0,canvas_height);
    ctx.rotate(getRad(180));
    ctx.scale(-1,1);
    ctx.translate(0,ground_float);
	let man_line_width = 5
	ctx.lineWidth = man_line_width
	//绘制地板
	ctx.beginPath()
	ctx.moveTo(0,0)
	ctx.lineTo(canvas_width,0)
	ctx.stroke() 

	//绘制火柴人
	//火柴人中心X坐标
	let man_x = 100

	//绘制腿
	//左腿
	let leg_height = 35
	ctx.beginPath()
	ctx.moveTo(man_x - leg_height,0)
	ctx.lineTo(man_x,leg_height)
	ctx.stroke()
	//右腿
	ctx.beginPath()
	ctx.moveTo(man_x + leg_height,0)
	ctx.lineTo(man_x,leg_height)
	ctx.stroke()

	//绘制躯干
	let body_len = 50
	ctx.beginPath()
	ctx.moveTo(man_x,leg_height)
	ctx.lineTo(man_x,leg_height+body_len)
	ctx.stroke()

	//绘制头部  
	let head_r = 20
	ctx.beginPath()
	ctx.arc(man_x,leg_height+body_len+head_r,head_r,0,2*Math.PI,false)
	ctx.stroke()

	//绘制右手
	//弧度设定
	//30度
	let hand_min_radian = Math.PI / 4
	//
	let hand_max_radian = Math.PI * 10/9
	
	let hand_speed = (hand_max_radian - hand_min_radian) / hand_last_time

	//绘制右手后臂
	let back_hand_radian = hand_min_radian
	let back_hand_len = 35
	let back_hand_start_y =  leg_height+body_len / 3.5
	let back_hand_end_x =  man_x + Math.cos(back_hand_radian) * back_hand_len
	let back_hand_end_y =  back_hand_start_y + Math.sin(back_hand_radian) *back_hand_len
	ctx.beginPath()
	ctx.lineWidth = man_line_width
	ctx.moveTo(man_x,back_hand_start_y)
	ctx.lineTo(back_hand_end_x, back_hand_end_y)
	ctx.stroke()

	
	//绘制右手前臂
	let front_hand_start_x = back_hand_end_x
	let front_hand_start_y = back_hand_end_y
	let front_hand_len = 40
	let front_hand_radian = hand_max_radian- (dt * hand_speed)
	front_hand_radian = front_hand_radian < hand_min_radian? hand_min_radian:front_hand_radian
	let front_hand_end_pos = calHandPos(front_hand_start_x, front_hand_start_y, front_hand_len, front_hand_radian)
	ctx.beginPath()
	ctx.lineWidth = man_line_width
	ctx.moveTo(front_hand_start_x,front_hand_start_y)
	ctx.lineTo(front_hand_end_pos.pos_x,front_hand_end_pos.pos_y)
	ctx.stroke()

	//标枪抛物线设定
	let curveStartPos = calHandPos(front_hand_start_x, front_hand_start_y, front_hand_len, hand_max_radian)
	let paraCurve = getParaCurve(curveStartPos.pos_x, curveStartPos.pos_y, end_x, 0)

	//标枪中点计算
	let tmp_x = curveStartPos.pos_x + dt * javelin_speed
	let javelin_middle_pos = {pos_x:tmp_x,pos_y:paraCurve.ParaCurveFunction(tmp_x)}
	let javelin_tan = paraCurve.GradientFunction(tmp_x)

	//绘制标枪
	let javelin_len = 50
	
	let javelin_pos = calPosByLAndTan(javelin_middle_pos.pos_x,javelin_middle_pos.pos_y, javelin_len, javelin_tan)
	ctx.beginPath()
	ctx.lineWidth = 8
	ctx.strokeStyle = "rgb(200,0,0)";
	ctx.moveTo(javelin_middle_pos.pos_x,javelin_middle_pos.pos_y)
	ctx.lineTo(javelin_pos.pos_x1,javelin_pos.pos_y1)
	ctx.stroke()
	ctx.beginPath()
	ctx.moveTo(javelin_middle_pos.pos_x,javelin_middle_pos.pos_y)
	ctx.lineTo(javelin_pos.pos_x2,javelin_pos.pos_y2)
	ctx.stroke()
	if(javelin_pos.pos_y1 <=0 || javelin_pos.pos_y2 <= 0){
		game_over = true
		game_begin = false
		calScore()
	}

	if(game_begin){
		requestAnimationFrame(draw_canvas)
	}
}

function draw_str_bar(){
	if(!game_begin && !game_over){
		bar_indicator_x = bar_indicator_x + str_bar_speed * (Date.now() - str_bar_time)/1000
		bar_indicator_x = bar_indicator_x % str_bar_width
		str_bar_time = Date.now()
	}
	let strength_bar_canvas = document.getElementById('strength_bar');
	strength_bar_canvas.width=str_bar_width;
	strength_bar_canvas.height=str_bar_height;
	var str_ctx = strength_bar_canvas.getContext('2d')
    str_ctx.translate(0,str_bar_height);
    str_ctx.rotate(getRad(180));
	str_ctx.scale(-1,1);
	str_ctx.lineWidth = 4


	str_ctx.beginPath()
	str_ctx.moveTo(0,0)
	str_ctx.lineTo(0,bar_height)
	str_ctx.lineTo(str_bar_width,bar_height)
	str_ctx.lineTo(str_bar_width,0)
	str_ctx.closePath()
	str_ctx.stroke()

	str_ctx.fillStyle='pink'
	str_ctx.fillRect(str_bar_mx - str_bar_mHalfWidth, 0,str_bar_mHalfWidth * 2, bar_height);

	str_ctx.beginPath()
	str_ctx.moveTo(bar_indicator_x,bar_height + 5)
	str_ctx.lineTo(bar_indicator_x - bar_indicator_Halfwidth,bar_indicator_y)
	str_ctx.lineTo(bar_indicator_x + bar_indicator_Halfwidth,bar_indicator_y)
	str_ctx.closePath()
	str_ctx.stroke()
	if(!game_begin && !game_over){
		requestAnimationFrame(draw_str_bar)
	}
}


function resetGame(){
	dt = 0
	game_over = false
	game_begin = false
	resetStrBar()
	requestAnimationFrame(draw_canvas)
	requestAnimationFrame(draw_str_bar)
}

function startGame(){
	if(game_begin){
		return
	}
	if(game_over){
		resetGame()
		return
	}
	dt = 0
	game_over = false
	game_begin = true
	beginTime = Date.now()
	calEndX()
	requestAnimationFrame(draw_canvas)
}


var stu_col_max = 7
var stu_row_max = 7
var stu_select_time = 3 //s
var stu_select_interval_time = 100 //ms
var stu_select_begin_time = undefined
var stu_select_result_hold_time = 4000 //ms
function getOneStu(){
	return randomInt(1, stu_col_max)+'列' + randomInt(1, stu_row_max) + '行'
}
function selectStuOver(){
	let stuSelectWrapper = document.getElementById('select_student_wrapper')
	stuSelectWrapper.style.display='none'
}
function selectIntervalTime(stu_show_div){
	if((Date.now() - stu_select_begin_time) / 1000 >= stu_select_time){
		stu_show_div.style.color='red'
		setTimeout(selectStuOver, stu_select_result_hold_time)
	}
	else{
		stu_show_div.innerHTML = getOneStu()
		setTimeout(selectIntervalTime, stu_select_interval_time, stu_show_div)
	}
}
function selectStudent(){
	stu_select_begin_time = Date.now()
	var stu_show_div = document.getElementById('select_student')
	var stuSelectWrapper = document.getElementById('select_student_wrapper')
	stuSelectWrapper.style.display='block'
	stu_show_div.style.color='black'
	setTimeout(selectIntervalTime, stu_select_interval_time,stu_show_div)
}

window.onload = function(){
	beginTime = Date.now()
	resetGame()
	delete_one_btn = document.getElementById('delete_one_btn')
	delete_one_btn.addEventListener("click", removeLastScore)

	delete_all_btn = document.getElementById('delete_all_btn')
	delete_all_btn.addEventListener("click", removeAllScores)

	select_student_btn = document.getElementById('select_student_btn')
	select_student_btn.addEventListener("click", selectStudent)

	start_btn = document.getElementById('start_btn')
	start_btn.addEventListener("click", startGame)
}